package com.itcast.donkey.fragments;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.Toast;

import com.itcast.donkey.R;
import com.itcast.donkey.activity.MainActivity;
import com.itcast.donkey.adapters.ToolExpandListViewAdapter;
import com.itcast.donkey.modles.ToolBoxModles;
import com.itcast.donkey.modles.UriModles;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by lanouhn on 16/9/3.
 */
public class ToolBoxOverseasFragment extends Fragment {

    private ExpandableListView listView;
    private List<ToolBoxModles.DestinationsBean> modlesList = new ArrayList<>();
    private ToolExpandListViewAdapter adapter;

    private SharedPreferences sp;
    private SharedPreferences.Editor etor;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tool_domestic, null);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        sp = getActivity().getSharedPreferences("config", Context.MODE_PRIVATE);
        etor = sp.edit();

        initView(getView());
        initData();
        initEvent();

    }

    private void initView(View view) {
        listView = (ExpandableListView) view.findViewById(R.id.listview_fragment_tool_domestic);

    }

    private void initData() {
        final String url = UriModles.TOOLBOX_URL;
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(url)
                        .build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        handler.sendEmptyMessage(0);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String values = response.body().string();
                        try {
                            JSONArray array = new JSONArray(values);
                            for (int i = 0; i < 3; i++) {
                                JSONObject object = array.getJSONObject(i);
                                JSONArray array2 = object.getJSONArray("destinations");
                                for (int j = 0; j < array2.length(); j++) {


                                    JSONObject object2 = array2.getJSONObject(j);
                                    ToolBoxModles.DestinationsBean destina = new ToolBoxModles.DestinationsBean();
                                    destina.setName_zh_cn(object2.getString("name_zh_cn"));
                                    destina.setId(object2.getInt("id"));
                                    destina.setImage_url(object2.getString("image_url"));
                                    destina.setName_en(object2.getString("name_en"));

                                    JSONArray array3 = object2.getJSONArray("children");

                                    List<ToolBoxModles.DestinationsBean.ChildrenBean> childList = new ArrayList<>();

                                    for (int k = 0; k < array3.length(); k++) {
                                        JSONObject object3 = array3.getJSONObject(k);
                                        ToolBoxModles.DestinationsBean.ChildrenBean child = new ToolBoxModles.DestinationsBean.ChildrenBean();
                                        child.setName_zh_cn(object3.getString("name_zh_cn"));
                                        child.setId(object3.getInt("id"));
                                        child.setImage_url(object3.getString("image_url"));
                                        child.setName_en(object3.getString("name_en"));
                                        child.setLocked(object3.getBoolean("locked"));
                                        child.setDestination_trips_count(object3.getInt("destination_trips_count"));
                                        child.setItems_count(object3.getInt("items_count"));
                                        childList.add(child);
                                    }
                                    destina.setChildren(childList);
                                    modlesList.add(destina);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        if (modlesList.size() > 0) {
                            handler.sendEmptyMessage(1);
                        } else {
                            handler.sendEmptyMessage(2);
                        }

                    }
                });

            }
        }).start();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Toast.makeText(getActivity(), "获取网络失败", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    adapter = new ToolExpandListViewAdapter(getActivity(), modlesList);
                    listView.setAdapter(adapter);
                    break;
                case 2:
                    Toast.makeText(getActivity(), "解析失败", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    private void initEvent() {

        listView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {

                Intent intent = new Intent(getActivity(), MainActivity.class);
                intent.putExtra("xia", 2);
                etor.putInt("areaID", modlesList.get(groupPosition).getId());
                etor.putInt("id", modlesList.get(groupPosition).getChildren().get(childPosition).getId());
                etor.putString("name", modlesList.get(groupPosition).getChildren().get(childPosition).getName_zh_cn());
                etor.putBoolean("isFirst", false);
                etor.commit();
                startActivity(intent);
                getActivity().finish();
                return true;
            }
        });
    }
}
